package com.wlyuan.index.remote.facade;

import com.wlyuan.core.domain.valueobj.OrderId;
import com.wlyuan.core.exception.AssertUtils;
import com.wlyuan.core.exception.ValueError;
import com.wlyuan.index.api.dto.order.OrderIndexDTO;
import com.wlyuan.index.api.dto.order.OrderReindexDTO;
import com.wlyuan.index.domain.source.adapter.OrderAdapter;
import com.wlyuan.order.api.IOrderService;
import com.wlyuan.order.dto.OrderFilterDTO;
import com.wlyuan.order.vo.OrderDetailVO;
import com.wlyuan.tools.Sort;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yuanjie
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class OrderFacade {
    @DubboReference(check = false)
    private IOrderService orderService;

    public OrderIndexDTO getOrderById(OrderId orderId) {
        AssertUtils.assertNotNull(orderId, new ValueError("订单ID不能为空"));
        return OrderAdapter.translate(orderService.getOrderById(orderId.getId()));
    }

    public List<OrderIndexDTO> getOrderByIds(Collection<OrderId> orderIds) {
        if (CollectionUtils.isEmpty(orderIds)) {
            return Collections.emptyList();
        }
        var ids = orderIds.stream()
                .map(OrderId::getId)
                .collect(Collectors.toList());
        var orders = (orderService.getOrderByIds(ids));
        return orders.stream()
//FIXME: 清空版本号                .peek(order -> order.setVersion(null))
                .map(OrderAdapter::translate)
                .collect(Collectors.toList());
    }

    public List<OrderId> listIds(long page, long size) {
        var reindex = new OrderReindexDTO();
        return this.listIds(reindex, page, size);
    }

    public List<OrderId> listIds(OrderReindexDTO reindex, long page, long size) {
        var filter = new OrderFilterDTO();
        BeanUtils.copyProperties(reindex, filter);
        filter.setSize(size);
        filter.setPage(page);
        var sorts = new ArrayList<Sort>();
        var sort = new Sort();
        sort.setAsc(false);
        sort.setName("id");
        sorts.add(sort);
        filter.setSort(sorts);
        var response = orderService.search(filter);
        if (null == response || CollectionUtils.isEmpty(response.getRecords())) {
            return Collections.emptyList();
        }
        return response.getRecords()
                .stream()
                .map(OrderDetailVO::getOrderId)
                .map(OrderId::new)
                .collect(Collectors.toList());
    }
}
